package com.factory.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author: sh
 * @Description: ImgUtil
 * @Date: 9:14 2019/7/1
 */
@Slf4j
public class ImgUtil {

    //data:image/jpeg;base64,
    private static String jpgBase64ImageStart = "data:image/jpg;base64,";
    private static String pngBase64ImageStart = "data:image/png;base64,";
    private static String jpegBase64ImageStart = "data:image/jpeg;base64,";

    /**
     * 添加图片base64头数据
     * @param base64Strt
     * @return
     */
    public static String dealToH5Image(String base64Strt){
        if(!base64Strt.startsWith(jpgBase64ImageStart)){
            return jpgBase64ImageStart + base64Strt;
        }
        return base64Strt;
    }


    /**
     * 图片转化成base64字符串
     *
     * @param imgPath
     * @return
     */
    public static String getBase64ImageStr(String imgPath) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        String imgFile = imgPath;// 待处理的图片
        InputStream in = null;
        byte[] data = null;
        String encode = null; // 返回Base64编码过的字节数组字符串
        // 对字节数组Base64编码
        Encoder encoder = Base64.getEncoder();
        try {
            // 读取图片字节数组
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            encode = encoder.encodeToString(data);
        } catch (IOException e) {
        	log.error("图片转化成base64字符串异常,{}",e);
        } finally {
            try {
                in.close();
            } catch (IOException e) {
            	log.error("图片转化成base64字符串关闭io异常,{}",e);
            }
        }
        return encode;
    }

    /**
     * base64字符串转化成图片
     *
     * @param imgData     图片编码
     * @param imgFilePath 存放到本地路径
     * @return
     * @throws IOException
     */
    @SuppressWarnings("finally")
    public static boolean generateBase64Image(String imgData, String imgFilePath ,String fileName){
    	log.debug("对字节数组字符串进行Base64解码并生成图片,{}",imgFilePath);
        if (imgData == null) // 图像数据为空
            return false;
        File f = new File(imgFilePath);
        
        if(!f.exists()) {
        	f.mkdirs();
        }
        
        Decoder decoder = Base64.getDecoder();
        OutputStream out = null;
        
        imgData = imgData.replaceFirst(jpgBase64ImageStart,"").
                replaceFirst(pngBase64ImageStart,"").
                replaceFirst(jpegBase64ImageStart,"");
        try {
            out = new FileOutputStream(imgFilePath + File.separator + fileName);
            // Base64解码
            byte[] bytes = decoder.decode(imgData);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            out.write(bytes);
            out.flush();
        } catch (FileNotFoundException e) {
            log.error("base64字符串转化成图片异常,{}",e);
        } catch (IOException e) {
            log.error("base64字符串转化成图片异常,{}",e);
        } finally {
            try {
            	if(null != out)
            		out.close();
			} catch (IOException e) {
				log.error("base64字符串转化成图片关闭io异常,{}",e);
			}
            return true;
        }
    }
}